// lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zywz/routes/app_router.dart';
import 'package:zywz/utils/AuthService.dart';
import 'package:zywz/utils/UserAdapter.dart';
import 'package:zywz/utils/user_company.dart';
import 'api/api_client.dart';
import 'api/chat/api_chat_asyn.dart';
import 'api/dio_client.dart';
import 'api/dio_client_chat.dart';
import 'bloc/ai_chat/ai_chat_bloc.dart';
import 'bloc/auth/auth_bloc.dart';
import 'bloc/auth/auth_event.dart';
import 'bloc/home/home_bloc.dart';
import 'bloc/listen/glod_bloc.dart';
import 'bloc/report/report_bloc.dart';
import 'bloc/service/service_bloc.dart';
import 'home.dart';
import 'models/user.dart';


void main() async {
  // runApp(const MyApp());

  // WidgetsFlutterBinding.ensureInitialized();
  // await Hive.initFlutter();
  WidgetsFlutterBinding.ensureInitialized();

  await Hive.initFlutter();
  // Hive.registerAdapter(CompanyAdapter());
  await Hive.openBox('settings');
  // await Hive.openBox<Company>('companies');
  Hive.registerAdapter(UserAdapter());
  Hive.registerAdapter(AppCompanyDtoAdapter());

  await Hive.openBox<User>('user_box');
  await Hive.openBox('loginBox');

  DioClient.initialize();
  DioClientChat.initialize();
  ApiClient.initialize(DioClient.instance);
  ApiChatAsynClient.initialize(DioClientChat.instance);

  // runApp(const HomeApp());
  runApp(const MyApp());
}




class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  final AuthService _authService = AuthService();

  @override
  void initState() {
    super.initState();
    // 监听重新登录事件
    // 监听认证状态变化
    _authService.authStatusStream.listen((status) {
      switch (status) {
        case AuthStatus.reLoginRequired:
          _handleReLogin();
          break;
        case AuthStatus.loggedIn:
        // 处理登录成功
          break;
        case AuthStatus.loggedOut:
        // 处理登出
          break;
        case AuthStatus.GoTHree:
          break;
      }
    });
  }

  void _handleReLogin() {
    // 显示重新登录对话框或跳转到登录页面
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _showReLoginDialog();
    });
  }

  void _showReLoginDialog() {
    showDialog(
      context: context,
      barrierDismissible: false, // 用户不能通过点击背景关闭对话框
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('会话过期'),
          content: Text('您的登录状态已过期，请重新登录。'),
          actions: <Widget>[
            TextButton(
              child: Text('重新登录'),
              onPressed: () {
                Navigator.of(context).pop();
                // 跳转到登录页面
                _navigateToLogin();
              },
            ),
          ],
        );
      },
    );
  }

  void _navigateToLogin() {
    // 执行跳转到登录页面的逻辑
    Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
  }



  @override
  Widget build(BuildContext context) {
    // AuthBloc must be provided at the top level for the router to use it.
    return BlocProvider<AuthBloc>(
      create: (context) => AuthBloc(
        apiClient: ApiClient.instance,
        userBox: Hive.box<User>('user_box'),
      )..add(AppStarted()), // Trigger auth check on start
      child: Builder(
        builder: (context) {
          // MultiBlocProvider for feature blocs
          return MultiBlocProvider(
            providers: [
              BlocProvider<HomeBloc>(
                create: (context) => HomeBloc(apiClient: ApiClient.instance),
              ),
              BlocProvider<ReportBloc>(
                create: (context) => ReportBloc(apiClient: ApiClient.instance),
              ),
              BlocProvider<ServiceBloc>(
                create: (context) => ServiceBloc(apiClient:ApiClient.instance)
              ),
              BlocProvider<AiChatBloc>(
                create: (context) => AiChatBloc(),
              ),
              BlocProvider<GlodBloc>(
                create: (context) => GlodBloc(),
              ),
            ],
            // The router needs access to AuthBloc, so it's inside the Builder
            child: RefreshConfiguration(
              headerBuilder: () => ClassicHeader(
                // 设置中文显示
                refreshingText: "正在加载...",
                idleText: "下拉加载",
                failedText: "刷新失败",
                completeText: "加载成功",
                releaseText: "松开加载",
              ),        // Configure the default header indicator. If you have the same header indicator for each page, you need to set this
                  // : () => WaterDropHeader(),        // Configure the default header indicator. If you have the same header indicator for each page, you need to set this
              footerBuilder:  () => ClassicFooter(),        // Configure default bottom indicator
              headerTriggerDistance: 80.0,        // header trigger refresh trigger distance
              springDescription:SpringDescription(stiffness: 170, damping: 16, mass: 1.9),         // custom spring back animate,the props meaning see the flutter api
              maxOverScrollExtent:100, //The maximum dragging range of the head. Set this property if a rush out of the view area occurs
              maxUnderScrollExtent:0, // Maximum dragging range at the bottom
              enableScrollWhenRefreshCompleted: true, //This property is incompatible with PageView and TabBarView. If you need TabBarView to slide left and right, you need to set it to true.
              enableLoadingWhenFailed: true, //In the case of load failure, users can still trigger more loads by gesture pull-up.
              hideFooterWhenNotFull: false, // Disable pull-up to load more functionality when Viewport is less than one screen
              enableBallisticLoad: true, // trigger load more by BallisticScrollActivity

              child: MaterialApp.router(
                // supportedLocales: [
                //   const Locale('zh'),
                // ],
                locale: const Locale('zh'),
                title: '章鱼问账',
                // theme: AppTheme.lightTheme,
                debugShowCheckedModeBanner: false,
                routerConfig: AppRouter(context.read<AuthBloc>()).router,
                builder: EasyLoading.init(),
              ),
            ),
          );
        },
      ),
    );
  }
}
